import {
  debounce
} from '@/utils'

export default {
  data() {
    return {
      sidebarElm: null,
      observer: null
    }
  },
  mounted() {
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
    this.sidebarElm = document.getElementsByClassName('sidebar-container')[0]
    this.sidebarElm && this.sidebarElm.addEventListener('transitionend', this.sidebarResizeHandler)

    const targetNode = document.querySelector(`.datacenter`)
    // 观察器的配置（需要观察什么变动）
    const config = {
      attributes: true,
      childList: true,
      subtree: true
    }

    // 当观察到变动时执行的回调函数
    const mutationCallback = (mutations) => {
      this.__resizeHandler()
    }

    // 创建一个观察器实例并传入回调函数
    this.observer = new MutationObserver(mutationCallback)

    // 以上述配置开始观察目标节点
    this.observer.observe(targetNode, config)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.__resizeHandler)
    if (this.observer) {
      this.observer.disconnect()
    }
    this.sidebarElm && this.sidebarElm.removeEventListener('transitionend', this.sidebarResizeHandler)
  },
  methods: {
    sidebarResizeHandler(e) {
      if (e.propertyName === 'width') {
        this.__resizeHandler()
      }
    }
  }
}
